<template>
  <div class="app-container">
    <el-form
      size="mini"
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item style="margin-right: 100px">
        <el-button type="primary" size="mini" @click="addVisible = true"
          >生成兑换码</el-button
        >
        <el-button
          type="danger"
          size="mini"
          icon="el-icon-delete"
          @click="handleDelete"
          >删除</el-button
        >
        <el-button type="primary" size="mini" @click="codeFuncVisisbleChange"
          >兑换功能开关</el-button
        >
      </el-form-item>
      <el-form-item prop="codeStatus">
        <el-select
          v-model="queryParams.codeStatus"
          placeholder="状态"
          @change="handleQuery"
          clearable
          size="mini"
        >
          <el-option label="未兑换" value="0" />
          <el-option label="已兑换" value="1" />
          <el-option label="已过期" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item prop="orderNum">
        <el-input
          v-model="queryParams.orderNum"
          placeholder="编号/产品名称"
          clearable
          size="mini"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="orderNum">
        <el-input
          v-model="queryParams.orderNum"
          placeholder="兑换人昵称/账号"
          clearable
          size="mini"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="orderList"
      @selection-change="handleSelectionChange"
      align="center"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="编号" prop="id" :show-overflow-tooltip="true" />
      <el-table-column
        label="产品"
        prop="goodsName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="规格">
        <template #default={row}>{{row.goodsStandard | goodsStandardFilter}}</template>
      </el-table-column>
      <el-table-column label="状态" prop="codeStatus">
        <template #default="{ row }">
          {{ row.codeStatus | filterStatus }}
        </template>
      </el-table-column>
      <el-table-column label="兑换人/账号">
        <template #default="{ row }">{{
          `${row.useNickName || ""}/${row.useUserName || ""}`
        }}</template>
      </el-table-column>
      <el-table-column label="备注" prop="codeDesc" />
      <el-table-column label="有效截止日期" width="160">
        <template #default="{ row }">
          {{ row.endTime | formatDates }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="160"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['system:exCode:detail']"
            >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            class="delete-btn"
            @click="updateCode(scope.row, 2)"
            v-if="scope.row.codeStatus != 2"
            v-hasPermi="['system:exCode:update']"
            >禁用
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="updateCode(scope.row, 0)"
            v-if="scope.row.codeStatus == 2"
            v-hasPermi="['system:exCode:update']"
            >启用
          </el-button>
          <el-button
            size="mini"
            type="text"
            class="delete-btn"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:exCode:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit="queryParams.pageSize"
      layout="sizes, prev, pager, next"
      @pagination="getList"
    />

    <!--兑换功能开关-->
    <el-dialog
      title="兑换功能开关"
      :visible.sync="codeFuncVisible"
      width="500px"
      append-to-body
    >
      <div style="display: flex">
        <div class="label" style="margin-right: 20px" v-hasPermi="['system:exCode:status']">兑换开关</div>
        <el-switch
          v-model="codeFunc"
          :active-value="1"
          :inactive-value="0"
        ></el-switch>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="codeFuncVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeCodeFunc">确 定</el-button>
      </span>
    </el-dialog>

    <!--兑换码新增-->
    <el-dialog
      title="生成兑换码"
      :visible.sync="addVisible"
      width="800px"
      @close="closeModal"
    >
      <el-form ref="addform" :model="addform" label-width="80px" size="mini">
        <el-form-item label="选择商品">
          <el-button @click="$refs.goodsPicker.show()">{{
            goodsInfo.length ? "重新选择" : "选择"
          }}</el-button>
        </el-form-item>
        <!-- 商品信息 -->
        <div v-if="goodsInfo.length" class="goods_wrapper_extend" style="margin-left: 80px">
          <el-table
            :data="goodsInfo"
            stripe
            size="mini"
            border
            style="width: 100%"
          >
            <el-table-column prop="goodsNumber" label="产品编号">
            </el-table-column>
            <el-table-column prop="desc" label="规格"> </el-table-column>
            <el-table-column label="产品封面图" align="center" width="100">
              <template #default="{ row }">
                <el-image
                  class="image"
                  fit="cover"
                  style="width: 40px; height: 40px"
                  :src="row.goodsCover[0]"
                  :preview-src-list="row.goodsCover"
                ></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="goodsName" label="产品名称">
            </el-table-column>
            <el-table-column prop="price" label="产品价格"> </el-table-column>
          </el-table>
        </div>
        <el-form-item
          label="APIKEY"
          prop="apiKey"
          :rules="{ required: true, message: '请输入apiKey' }"
        >
          <el-input v-model="addform.apiKey" placeholder="apikey"></el-input>
        </el-form-item>
        <el-form-item
          label="生成数量"
          prop="codeNum"
          :rules="{ required: true, message: '请输入生成数量' }"
        >
          <el-input
            v-model="addform.codeNum"
            type="number"
            placeholder="生成数量"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="截止日期"
          prop="endTime"
          :rules="{ required: true, message: '请选择截止时间' }"
        >
          <el-date-picker
            v-model="addform.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="addform.codeDesc"></el-input>
        </el-form-item>
        <el-form-item style="text-align: center" label-width="0">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveCode">生成并导出</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <goodsPicker
      ref="goodsPicker"
      @selected="(res) => (goodsInfo = res)"
    ></goodsPicker>
  </div>
</template>

<script>
import { formatDate } from "@/utils";
import goodsPicker from "@/components/goodsPicker";
import {
  exCodeList,
  exCodeConfigStatus,
  updateExCodeConfigStatus,
  addExchangeCode,
  delExCode,
  exchangeCodeStatus,
} from "@/api/system/exCode";

export default {
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      orderNums: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderType: null,
        userType: null,
        orderNum: null,
        phonenumber: null,
        nickName: null,
        startTime: null,
        endTime: null,
        time: null,
      },
      codeFuncVisible: false,
      codeFunc: 1,
      addVisible: false,
      addform: {},
      openChooseGoods: false,
      goodsInfo: "",
    };
  },
  filters: {
    formatDates(value) {
      return formatDate(value);
    },
    // 状态(0：未兑换1：已兑换2：已禁用3：已过期)
    filterStatus(value) {
      return {
        0: "未兑换",
        1: "已兑换",
        2: "已禁用",
        3: "已过期",
      }[value];
    },
    goodsStandardFilter(value) {
      try {
        let json_val = JSON.parse(value)
        let ret
        if (Array.isArray(json_val)) {
          ret = json_val[0] && json_val[0].desc
        } else {
          ret = json_val.desc
        }
        return ret
      } catch {

      }
    }
  },
  components: {
    goodsPicker,
  },
  created() {
    this.getList();
    console.log(process.env.VUE_APP_BASE_API)
  },
  methods: {
    // 保存兑换码
    saveCode() {
      this.$refs["addform"].validate((res) => {
        if (res) {
          this.addform.goodsId = this.goodsInfo.map((item) => item.goodsId)[0];
          // 'goodsStandard'
          let goodsStandard = this.goodsInfo.map((item) => {
            let { length, type, price, desc } = item;
            return {
              length,
              type,
              price,
              desc,
              fixedPrice: null,
              scale: null,
              discountsPrice: null,
              returnMoney: null,
              groupPrice: null,
            };
          })[0]
          this.addform.goodsStandard = JSON.stringify(goodsStandard)
          addExchangeCode(this.addform).then((res) => {
            this.$message.success('生成成功!');
            var link = document.createElement('a');
            //设置下载的文件名
            link.download = res.msg;
            link.style.display = 'none';
            //设置下载路径
            link.href = `${process.env.VUE_APP_BASE_API}/common/download?delete=true&fileName=${res.msg}`;
            //触发点击
            document.body.appendChild(link);
            link.click();
            //移除节点
            document.body.removeChild(link);
            this.addVisible = false
          });
        } else {
          return false;
        }
      });
    },

    // 关闭弹窗
    closeModal() {
      this.getList();
      this.addform = {};
      this.goodsInfo = [];
    },

    // 更改状态按钮
    codeFuncVisisbleChange() {
      this.codeFuncVisible = true;
      exCodeConfigStatus().then((res) => {
        this.codeFunc = res.data;
      });
    },

    // 更改兑换功能状态
    changeCodeFunc() {
      updateExCodeConfigStatus(this.codeFunc).then((res) => {
        this.codeFuncVisible = false;
        this.$message({
          message: "操作成功！",
          type: "success",
        });
      });
    },

    // 查询列表
    getList() {
      this.loading = true;
      exCodeList(this.queryParams).then((response) => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.orderNums = selection.map((item) => item.orderNum);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // 查看详情
    handleView(row) {
      this.$router.push({
        name: "exCodeDetails",
        params: {
          id: row.id,
        },
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除选中兑换码？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delExCode(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },

    // 启用、禁用兑换码
    updateCode(row, status) {
      let { id } = row;
      exchangeCodeStatus({ id, status }).then((res) => {
        this.$message.success("操作成功！");
        this.getList();
      });
    },
  },
};
</script>

